package com.njitzx.service.impl;

import com.njitzx.entity.vo.CategoryVO;
import com.njitzx.exception.CategoryException;
import com.njitzx.entity.po.Category;
import com.njitzx.mapper.AttributeMapper;
import com.njitzx.mapper.CategoryMapper;
import com.njitzx.mapper.GoodsMapper;
import com.njitzx.service.CategoryService;
import org.checkerframework.checker.units.qual.C;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


/**
 * <p>
 * 分类表 服务实现类
 * </p>
 *
 * @author 周鑫
 * @since 2024-08-20
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class CategoryServiceImpl implements CategoryService {

    private final CategoryMapper categoryMapper;

    private final GoodsMapper goodsMapper;

    private final AttributeMapper attributeMapper;

    /**
     * 分类表分页查询
     *
     * @return
     */
//    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
//    @Override
//    public Map<String, Object> findPage(Integer type, Integer pageNum, Integer pageSize) {
//        Map<String,Object> map=new HashMap<>();
//        List<Category> select = categoryMapper.select(new Category());
//        if (pageNum != null && pageSize != null) {
//            PageHelper.startPage(pageNum, pageSize);
//        }
//        if (type == null || type == 3) {
//            //查询所有
//
//        }
//        if (type == 1) {
//             map.put("list",select);
//        }
//        if (type == 2) {
//            //拿到所有的一级分类
//            List<Category> first = select.stream()
//                    .filter(item -> item.getCatPid() == 0)
//                    .collect(Collectors.toList());
//            first.stream().filter(item->item.getCatPid().equals())
//        }
//
//    }
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public Map<String, Object> findPage(Integer type, Integer pageNum, Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        // 获取所有分类
        List<Category> categories = categoryMapper.select(new Category());
        System.out.println("cat"+categories);
        // 将 Category 转换为 CategoryVO，并构建分类树
        List<CategoryVO> categoryTree = buildCategoryTree(categories, 0);
        // 根据 type 参数过滤数据
        List<CategoryVO> filteredCategories;
        if (type == null || type == 3) {
            filteredCategories = categoryTree; // 全部层级
        } else if (type == 1) {
            filteredCategories = categoryTree.stream()
                    .filter(categoryVO -> categoryVO.getCatLevel() == 0)
                    .collect(Collectors.toList()); // 只返回一级分类
        } else if (type == 2) {
            filteredCategories = categoryTree.stream()
                    .filter(categoryVO -> categoryVO.getCatLevel() == 0)
                    .peek(categoryVO -> categoryVO.setChildren(
                            categoryVO.getChildren().stream()
                                    .filter(child -> child.getCatLevel() == 1)
                                    .collect(Collectors.toList())))
                    .collect(Collectors.toList()); // 返回一级分类及其下的二级分类
        } else {
            filteredCategories = new ArrayList<>();
        }

        // 分页处理
        if (pageNum != null && pageSize != null) {
            int total = filteredCategories.size(); //总条数
            int fromIndex = (pageNum - 1) * pageSize; //起始
            int toIndex = Math.min(fromIndex + pageSize, total);
            if (fromIndex > total) {
                filteredCategories = Collections.emptyList();
            } else {
                filteredCategories = filteredCategories.subList(fromIndex, toIndex);
            }
            result.put("total", total);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("list", filteredCategories);
        } else {
            result.put("list", filteredCategories);
        }

        return result;
    }

    // 构建分类树的方法
    private List<CategoryVO> buildCategoryTree(List<Category> categories, Integer parentId) {
        List<CategoryVO> tree = new ArrayList<>();
        for (Category category : categories) {
            if (category.getCatPid().equals(parentId)) {
                // 转换 Category 到 CategoryVO
                CategoryVO categoryVO = new CategoryVO();
                categoryVO.setCatId(category.getCatId());
                categoryVO.setCatName(category.getCatName());
                categoryVO.setCatPid(category.getCatPid());
                categoryVO.setCatLevel(category.getCatLevel());
                // 递归构建子分类树
                List<CategoryVO> children = buildCategoryTree(categories, category.getCatId());
                categoryVO.setChildren(children);
                tree.add(categoryVO);
            }
        }
        return tree;
    }



    /**
     * 根据主键查询分类表
     *
     * @param catId
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public Category findById(Serializable catId) {
        return categoryMapper.selectById(catId);
    }

    /**
     * 分类表新增
     *
     * @param category
     */
    @Override
    public void add(Category category) {
        categoryMapper.insert(category);
    }

    /**
     * 修改分类表
     * @param category
     */


    /**
     * 根据主键删除分类表
     *
     * @param catId
     */
    @Override
    public void removeById(Integer catId) {
        //1.判断分类下面 是否有商品  如果有商品
        Integer counts = goodsMapper.selectIsExistCategory(catId);
        if (counts > 0) {
            throw new CategoryException("该分类下面有商品，不能删除");
        }
        //2.获取要删除的分类和子分类id
        List<Integer> deleteCatIds = new ArrayList<>();

        //third是三级分类的id
        List<Integer> thirdCatIds = new ArrayList<>();

        deleteCatIds.add(catId); //将当前的id添加上去
        //如果是三级分类 不用递归查询
        findCategory(catId, deleteCatIds, thirdCatIds);
        //是的就是递归查询你
        //3.将分类标记删除
        System.out.println("删除的id"+deleteCatIds);
        categoryMapper.deleteByIds(deleteCatIds);
        //将分类删除
        //4.将分类下的属性标记删除 根据三级id
        if (!thirdCatIds.isEmpty()) {
            attributeMapper.deleteByIds(thirdCatIds);
        }
    }

    private void findCategory(Integer catId, List<Integer> deleteCatIds, List<Integer> thirdCatIds) {
        List<Category> categoryList = categoryMapper.selectChildrenByPid(catId); //根据复id找到分类
        //遍历分类 递归下去
        categoryList.forEach(category -> {
            //判断是否为三级分类
            if (category.getCatLevel() == 2) {  //如果是三级分类的id 添加进来
                thirdCatIds.add(category.getCatId());
            }
            findCategory(category.getCatId(), deleteCatIds, thirdCatIds);
            deleteCatIds.add(category.getCatId());
        });
    }

    private List<Integer> finaAllSubCategoryIds(Integer catId) {
        List<Integer> ids = categoryMapper.findSubCategoryIds(catId);
        List<Integer> allIds = new ArrayList<>(ids);  // 创建一个新列表，保存所有的ID
        // 遍历当前ID列表，并递归获取每个子分类的所有子分类ID
        for (Integer id : ids) {
            allIds.addAll(finaAllSubCategoryIds(id));
        }
        return allIds;  // 返回完整的ID列表
    }


    @Override
    public void modify(Category category) {
        categoryMapper.update(category);
    }

}
